package com.richapp.launcher.serialport.gateway.command;

import android.content.Context;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.jack.util.bytes.ByteUtil;
import com.jack.util.hex.HexUtil;
import com.richapp.launcher.database.system.dao.BoxModelDao;
import com.richapp.launcher.gpio.GPIOServer;
import com.richapp.launcher.net.mobile.server.UserServer;
import com.richapp.launcher.net.remote.RemoteClient;
import com.richapp.launcher.serialport.gateway.ControlInstructionMessage;
import com.richapp.launcher.serialport.gateway.GatewayServer;
import com.richapp.launcher.serialport.gateway.GatewaytConstant;
import com.richapp.net.util.HexTool;

import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class InfraredStudyCmd extends BasicCommand {

	private static byte[] endbytes = null;

	private static InfraredStudyCmd resetCmd = null;

	private static Context cxt;

	private InfraredStudyCmd() {
		endbytes = new byte[]{(byte)0xA5,0x5A,0x5A};
	}


	public static InfraredStudyCmd getInstance(Context context){
		if(resetCmd == null){
			resetCmd = new InfraredStudyCmd();
			cxt = context;
		}
		return resetCmd;
	}

	public void InfraredControlCmd(String cpuBoxId,String deviceId, String deviceNumber,String way,String studyKey){
		this.PacketHead = "FF001900";
		this.ID = deviceId;
		this.Number = deviceNumber;
		ControlInstructionMessage cim = new ControlInstructionMessage(cpuBoxId,deviceId,deviceNumber,way);
		cim.setHexInstruction(combinationControlCMD());
		cim.setKey(studyKey);
		cim.setInstructionFlag(GatewaytConstant.INSTRUCTION_FLAG_INFRARED_STUDY);
		GatewayServer.getInstance().writeMessage(cim);

	}

	private String combinationControlCMD(){
		String cmd = PacketHead+ID+Number+"00000000000000000000";
		String checkCode = HexUtil.sumCheck(cmd);
		return cmd+checkCode;
	}

	/**
	 * FF 0020 001500 014F4B 000000 000000 000001 CF
	 * FF 0101 112233 445566 778899 AABBCC DDEE07 FA
	 * FF 0102 101112 131415 161718 191A1B 1C1D02 3D
	 * FF 0103 202122 232425 262728 292A2B 2C2D03 1E
	 * FF 0104 303132 333435 363738 393A3B 3C3D03 FF
	 * FF 0105 404142 434445 464748 494A4B 4C4D04 E0
	 * FF 0106 505152 535455 565758 595A5B 5C5D05 C1
	 * FF 0207 606162 636465 666768 696AA5 5AA507 03
	 * @param cmd
     */
	@Override
	public void analyticalCmd(String cmd) {

	}

	@Override
	public void analyticalInfrared(ControlInstructionMessage message) {
		try{
			String cmd = message.getResultData();

			Log.v(getClass().getName(), "收到红外学习的结果"+cmd);
			byte[] data = HexUtil.HexToByteArr(cmd);

			String deviceId = "";
			String deviceNumber = "";

			ByteArrayOutputStream bos = new ByteArrayOutputStream();

			ByteBuffer byteBuffer = ByteBuffer.allocate(19);
			int index = 0;
			int i = 0;
			for(byte b : data){
				byteBuffer.put(b);
				index++;

				if(index%19 == 0){
					byte[] rows = byteBuffer.array();
					String rowHex = HexUtil.ByteArrToHex(rows);
					if(i != 0){
						int end = -1;
						if((end = rowHex.indexOf("A55AA5")) != -1){
							bos.write(ByteUtil.subBytesStart(rows,2,end/2-2));
						}else{
							bos.write(ByteUtil.subBytesStart(rows,2,15));
						}
					}else{
						deviceId = rowHex.substring(8,10);
						deviceNumber = rowHex.substring(10,14);
					}
					i++;
					byteBuffer.clear();
				}
			}

			byte[] result = bos.toByteArray();

			Map<String,Object> map = new HashMap<String,Object>();
			map.put("type",57);
			map.put("currentBoxCpuId",new BoxModelDao(cxt).getCurrentBox().getBoxCpuId());
			map.put("userName",new BoxModelDao(cxt).getCurrentBox().getUserName());
			map.put("studyKey",message.getKey());
			map.put("studyFlag","true");
			map.put("controlData",HexTool.ByteArrToHex(result));

			String msg = JSON.toJSONString(map);
			//发送用户数据
			UserServer.getInstance().sendAllUsersMessage(msg);
			//转发到服务器
			RemoteClient.getInstance().sendMessage(msg);

			GPIOServer.getInstance().infraredStudySuccessed();
		}catch (Exception e){
			Log.e(getClass().getName(),e.getMessage());
		}
	}
}
